package com.gitee.feizns.explore.data_structure.linked_list.singly.addTwoNumbers;

import com.gitee.feizns.explore.data_structure.linked_list.singly.ListNode;

/**
 * @author feizns
 * @since 2020/3/6
 */
public class AddTwoNumbers2 {

    public static void main(String[] args) {
        addTwoNumbers(create1(), create()).print();
    }

    private static ListNode create1() {
        ListNode ret = new ListNode(1);
        ret.next = new ListNode(2);
        return ret;
    }

    private static ListNode create() {
        ListNode ret = new ListNode(2);
        return ret;
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode la = dummy;
        int carry = 0;
        while ( l1 != null || l2 != null ) {
            int sum = carry;
            if ( l1 != null ) {
                sum += l1.val;
                l1 = l1.next;
            }
            if ( l2 != null ) {
                sum += l2.val;
                l2 = l2.next;
            }
            la.next = new ListNode(sum % 10);
            la = la.next;
            carry = sum / 10;
        }
        if ( carry != 0 )
            la.next = new ListNode(carry);
        return dummy.next;
    }

}

